import React, { useState, useEffect, useMemo } from "react";
import { Button, Select, Steps, theme, Typography, Form, Input } from "antd";
const { Title } = Typography;
import NewsEditor from "../../../components/news-manage/NewsEditor";
import { useParams,useNavigate} from "react-router-dom";
import {ArrowLeftOutlined} from '@ant-design/icons';
import axios from "axios";
//富文本编辑器 使用Draft Wysiwyg

//content属性就是步骤的内容属性
const steps = [
  {
    title: "基本信息",
    description: "新闻标题 新闻分类",
  },
  {
    title: "新闻内容",
    description: "撰写新内容",
  },
  {
    title: "提交新闻",
    description: "保存草稿或者提交审核",
  },
];
export default function NewsUpdate() {
  const navigator = useNavigate();
  /* steps步骤栏所需函数与状态 */
  const [current, setCurrent] = useState(0);
  const { token } = theme.useToken();
  const next = () => {
    // 校验第一部表单是否填写
    if (current == 0) {
      // 校验新闻标题是否填写
      if (!newsTitle || !newsCategory) {
        alert("请填写完整信息");
        return;
      }
    } else if (current == 1) {
      //如果没有填写内容
      if (news.content === "" || news.content === "<p></p>\n") {
        alert("请填写内容");
        return;
      }
    }
    setCurrent(current + 1);
  };
  const prev = () => {
    setCurrent(current - 1);
  };
  const items = steps.map((item) => ({ key: item.title, title: item.title }));
  const contentStyle = {
    color: token.colorTextTertiary,
    backgroundColor: token.colorFillAlter,
    borderRadius: token.borderRadiusLG,
    border: `1px dashed ${token.colorBorder}`,
    marginTop: 16,
  };

  /* step 0 表单所需函数 */
  // 设置newsTitle与newsCategory 后续设置newsContent来保存
  const [newsTitle, setNewsTitle] = useState("");
  const [newsCategory, setNewsCategory] = useState("");
  const [categoryList, setCategoryList] = useState([]);
  const [newsContent, setNewsContent] = useState("");
  const { id } = useParams(); // 获取当前路由的参数id
  const [form] = Form.useForm();
  useEffect(()=>{
    axios.get(`http://localhost:3000/news/${id}?_expand=category&_expand=role`).then((res)=>{
      const newsData = res.data;      
      // 设置状态
      setNewsContent(newsData.content || "")
      setNewsTitle(newsData.title || "")
      setNewsCategory(newsData.categoryId || "")
      
      // 设置表单值
      form.setFieldsValue({
        title: newsData.title || "",
        categoryId: newsData.categoryId || ""
      });
    }).catch(error => {
      console.error('获取数据失败:', error);
    })
  },[id, form])
  
  useEffect(() => {
    axios.get("http://localhost:3000/categories").then((res) => {
      // 设置列表数据
      const formattedData = res.data.map((item) => ({
        label: item.title,
        value: item.id,
      }));
      setCategoryList(formattedData);
    });
  }, []);

  const handleChange = (value) => {
    setNewsCategory(value);
  };

  /* step 1 表单所需函数与状态 */

  /* step 2 表单所需函数与状态 */
  // 整合新闻信息 提交新闻
  const news = useMemo(
    () => ({
      title: newsTitle,
      categoryId: newsCategory,
      content: newsContent,
    }),
    [newsTitle, newsCategory, newsContent]
  );

  /* step 3 表单所需函数与状态 */
  const user = JSON.parse(localStorage.getItem("token"));
  const handleSave = (auditState) => {
    axios
      .patch(`http://localhost:3000/news/${id}`, {
        ...news,
        region: user.region ? user.region : "全球",
        auditState: auditState, //重置审核状态
      }).then(()=>{
        navigator("/news-manage/draft");
      })
      .catch((error) => {
        console.error("Save error:", error);
      });
  };

  //content编写
  steps[0].content = (
    <Form
      form={form}
      name="basic"
      labelCol={{ span: 8 }}
      wrapperCol={{ span: 16 }}
      style={{ maxWidth: 600, marginTop: "30px" }}
      autoComplete="off"
    >
      <Form.Item
        label="新闻标题"
        name="title"
        rules={[{ required: true, message: "请输入新闻标题!" }]}
      >
        <Input
          onChange={(e) => setNewsTitle(e.target.value)}
        />
      </Form.Item>

      <Form.Item
        label="新闻分类"
        name="categoryId"
        rules={[{ required: true, message: "请选择新闻分类!" }]}
      >
        <Select
          showSearch
          options={categoryList}
          onChange={handleChange}
          placeholder="请选择新闻分类"
        />
      </Form.Item>
    </Form>
  );
  //content编写
  steps[1].content = (
    <NewsEditor
      content={newsContent}
      getContent={(value) => {
        setNewsContent(value);
      }}
    />
  );
  //content编写
  steps[2].content = <></>;

 const onBack = () => {
  window.history.back();
}
  return (
    <div>
      {
        current < steps.length - 1 &&(
          <Button
          type="text"
          icon={<ArrowLeftOutlined />}
          onClick={onBack}
          className="back-button"
          style={{
            marginRight: `16px`,
            display:'inline-block',
            alignItems: "center",
            justifyContent: "center",
            width: `32px`,
            height: `32px`,
            borderRadius: `6px`,
            transition: `all 0.2s`,
            hover :{
              backgroundColor: `#f5f5f5`,
            }
          }}
          />
        )}
      <Title>修改新闻</Title>
      <Steps current={current} items={items} />
      <div style={contentStyle}>{steps[current].content}</div>
      <div style={{ marginTop: 24 }}>
        {/* 确保下一步不会出现在最后的步骤 */}
        {current < steps.length - 1 && (
          <Button
            htmlType="submit"
            onClick={() => {
              next();
            }}
          >
            下一步
          </Button>
        )}
        {current === steps.length - 1 && (
          <>
            <Button
              type="primary"
              onClick={() => {
                handleSave(0);
                
              }}
            >
              保存草稿
            </Button>
            <Button
              type="primary"
              danger
              onClick={() => {
                handleSave(1);
              }}
            >
              提交审核
            </Button>
          </>
        )}
        {current > 0 && (
          <Button style={{ margin: "0 8px" }} onClick={() => prev()}>
            上一步
          </Button>
        )}

      </div>
    </div>
  );
}
